<template>
  <div class="work_stage_material" v-if="dialogVisible">
    <el-dialog
      title="工序上料"
      width="1400px"
      v-dialogDrag
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      customClass="mes_dialog">
      <div class="material_wrapper"
           v-loading="isLoading">
        <div class="mes_tab_close">
          <el-tabs v-model="tabsIndex" type="card">
            <el-tab-pane label="上料" name="materialCharging">
            </el-tab-pane>
            <el-tab-pane label="工装夹具上料" name="toolCharging">
            </el-tab-pane>
          </el-tabs>
        </div>
        <div v-if="tabsIndex === 'materialCharging'"
             class="batch_cont table_container">
          <div class="table_title">批量上料</div>
          <el-table
            border
            :data="batchMaterialList"
            ref="batchList"
            style="width: 100%"
            :max-height="`${batchMaterialListHeight}`"
            class="table_dialog">
            <mes-col-comp
              :key="index"
              v-for="(column, index) in materialCol.batchCol"
              :column="column">
            </mes-col-comp>
            <el-table-column
              label="上料周转码/采购批次号"
              :resizable="false"
              min-width="160"
              class-name="cell_padding">
              <template slot-scope="scope">
                <el-select
                  v-model.trim="scope.row.turnoverOrPurchaseNumberTransfer"
                  multiple
                  filterable
                  allow-create
                  remote
                  reserve-keyword
                  default-first-option
                  placeholder="请输入周转码/采购批次号"
                  @change="(val) => selectChange(val, scope.row)"
                  @focus="autoFocus(scope.row)"
                  :remote-method="queryTurnoverNumber">
                  <el-option
                    v-for="item in curTurnoverNumber"
                    :key="item"
                    :label="item"
                    :value="item">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="tabsIndex === 'materialCharging'"
             class="singleton_cont table_container">
          <div class="table_title">单件上料</div>
          <el-table
            border
            :data="singleMaterialList"
            ref="singleList"
            style="width: 100%"
            :max-height="`${singleMaterialListHeight}`"
            v-table-scroll='inputBlur'
            class="table_dialog">
            <mes-col-comp
              :key="index"
              v-for="(column, index) in materialCol.singletonCol"
              :column="column">
            </mes-col-comp>
            <el-table-column
              label="序列号"
              min-width="180"
              fixed="right"
              class-name="cell_padding"
              prop="subMaterialSerialNumberTransfer">
              <template slot-scope="scope">
                <el-select
                  v-model.trim="scope.row.subMaterialSerialNumberTransfer"
                  multiple
                  :multiple-limit="1"
                  filterable
                  allow-create
                  default-first-option
                  remote
                  placeholder="请输入序列号"
                  @focus="autoFocus(scope.row, true)"
                  @change="(val) => serialSelect(val, scope.row)"
                  @remove-tag="(val) => removeTag(val, scope.row)"
                  :remote-method="querySerialNumber">
                  <el-option
                    v-for="item in curSingleMaterialNumber"
                    :key="item.serialNumber"
                    :label="item.serialNumber"
                    :value="item.serialNumber">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              label="上料周转码/采购批次号"
              :resizable="false"
              fixed="right"
              min-width="180"
              class-name="cell_padding"
              prop="turnoverOrPurchaseNumberTransfer">
              <template slot-scope="scope">
                <el-select
                  v-model.trim="scope.row.turnoverOrPurchaseNumberTransfer"
                  multiple
                  :multiple-limit="1"
                  filterable
                  allow-create
                  default-first-option
                  remote
                  placeholder="请输入周转码/采购批次号"
                  @focus="autoFocus(scope.row)"
                  @change="(val) => selectChange(val, scope.row)"
                  :remote-method="queryTurnoverNumber">
                  <el-option
                    v-for="item in curTurnoverNumber"
                    :key="item"
                    :label="item"
                    :value="item">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="tabsIndex === 'toolCharging'"
             class="tool_cont table_container">
          <div class="table_title">工装夹具上料</div>
          <el-table
            border
            :data="resourceList"
            ref="resourceList"
            style="width: 100%"
            max-height="428"
            v-table-scroll="inputBlur"
            class="table_dialog">
            <mes-col-comp
              :key="index"
              v-for="(column, index) in materialCol.toolCol"
              :column="column">
            </mes-col-comp>
            <el-table-column
              label="资源序列号"
              :resizable="false"
              min-width="180"
              class-name="cell_padding"
              align="center">
              <template slot-scope="scope">
                <el-input
                  v-model.trim="scope.row.resourceSerialNumber"
                  placeholder="请输入内容"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <span slot="footer" class="mes_btn">
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="dialogVisible=false">取消</el-button>
      </span>
      <input type="text" id="hidden_input"/>
    </el-dialog>
  </div>
</template>

<script>
import materialCol from './materialCol'

export default {
  name: 'WorkStageMaterial',
  data() {
    return {
      dialogVisible: false, // 显示隐藏
      workStageListIds: null, // 已选择工序列表
      isLoading: false, // 加载中
      curMaterialList: [], // 当前物料列表
      curTurnoverNumber: [], // 当前周转批次下拉列表
      curSingleMaterialNumber: [], // 当前序列号下拉列表
      tabsIndex: 'materialCharging', // 上料tabs
      materialCol: materialCol, // 列配置
      saveState: false, // 保存状态，避免重复提交
    }
  },
  computed: {
    // 无序列号子物料表
    batchMaterialList() {
      return this.$store.state.workshopBench.workStageMaterialList.batchMaterialList || []
    },
    // 有序列号子物料表
    singleMaterialList() {
      return this.$store.state.workshopBench.workStageMaterialList.singleMaterialList || []
    },
    // 工装夹具上料表
    resourceList() {
      return this.$store.state.workshopBench.workStageMaterialList.resourceList || []
    },
    // 批量上料table高度
    batchMaterialListHeight() {
      let height = 200 - this.singleMaterialList.length * 40
      return height > 0 ? 180 + height : 180
    },
    // 单件上料table高度
    singleMaterialListHeight() {
      let height = 180 - this.batchMaterialList.length * 40
      return height > 0 ? 200 + height : 200
    },
    // 物料周转码大对象
    materialNumber() {
      return this.$store.state.workshopBench.materialNumber
    },
  },
  methods: {
    // 显示弹框
    async openDialog(data) {
      this.dialogVisible = true
      this.workStageListIds = data.map(item => item.id)
      this.tabsIndex = 'materialCharging'
      this.isLoading = true
      await this.getMaterialNumber()
      await this.init()
    },
    // 初始化方法
    init() {
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/turnoverworkstage/turnoverWorkstage/provideMaterial',
        data: {
          ids: this.workStageListIds
        },
        noCommit: true,
      }).then(res => {
        let data = res.data
        data.singleMaterialList = data.singleMaterialList.map(item => this.initSelectItem(item, ['turnoverOrPurchaseNumber', 'subMaterialSerialNumber', 'subWorkorderId']))
        data.batchMaterialList = data.batchMaterialList.map(item => this.initSelectItem(item, ['turnoverOrPurchaseNumber', 'subWorkorderId']))
        this.$store.commit('SetState', {
          module: 'workshopBench',
          state: 'workStageMaterialList',
          data: data
        })
        this.isLoading = false
      }).catch(() => {
        this.isLoading = false
      })
    },
    // 初始化周转码及序列号
    initSelectItem(item, keys) {
      keys.map(key => {
        if (item[key]) {
          this.$set(item, key + 'Transfer', item[key].split(','))
        } else {
          this.$set(item, key + 'Transfer', [])
        }
      })
      return item
    },
    // 获取上料周转码/采购批次号
    getMaterialNumber() {
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/turnoverworkstage/turnoverWorkstage/getTurnoverNumAndSerialNum',
        data: {'ids': this.workStageListIds},
        module: 'workshopBench',
        state: 'materialNumber'
      })
    },
    // 格式化保存数据
    postData() {
      return {
        ids: this.workStageListIds,
        singleMaterialList: this.singleMaterialList.map(item => {
          item.turnoverOrPurchaseNumber = item.turnoverOrPurchaseNumberTransfer.join(',')
          item.subMaterialSerialNumber = item.subMaterialSerialNumberTransfer.join(',')
          item.subWorkorderId = item.subWorkorderIdTransfer.join(',')
          return item
        }),
        batchMaterialList: this.batchMaterialList.map(item => {
          item.turnoverOrPurchaseNumber = item.turnoverOrPurchaseNumberTransfer.join(',')
          item.subWorkorderId = item.subWorkorderIdTransfer.join(',')
          return item
        }),
        resourceList: this.resourceList,
      }
    },
    // 提交
    submit() {
      if (this.saveState) return;
      this.saveState = true
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/turnoverworkstage/turnoverWorkstage/saveProvideMaterial',
        data: this.postData(),
        noCommit: true
      }).then(() => {
        this.$message({
          type: 'success',
          message: '保存成功',
          duration: 1500,
          center: true
        })
        this.dialogVisible = false
        this.$emit('submitSuccess')
      }).finally(() => {
        this.saveState = false
      })
    },
    /**
     * 搜索框获取焦点
     * @param row 单行数据
     */
    autoFocus(row, type) {
      if (row === undefined) return
      if (type) {
        this.$nextTick(() => {
          this.hideSelect()
        })
      }
      // 获取当前物料的所有下拉列表
      this.curMaterialList = this.materialNumber[row.materialNumber] || []
      // 设置当前序列号下拉列表
      this.curSingleMaterialNumber = this.curMaterialList.filter(item => item.disabled !== true && item.serialNumber)
      let set = new Set(this.curMaterialList.reduce((pre, cur) => [...pre, cur.turnoverNumber], []))
      // 设置当前周转码下拉列表
      this.curTurnoverNumber = [...set]
    },
    /**
     * 获取搜索到的周转码列表
     * @param string 输入的字符
     */
    queryTurnoverNumber(string) {
      let curList = this.curMaterialList
      // 如果输入不为空
      if (string) {
        curList = this.curMaterialList.filter(item => item.turnoverNumber.startsWith(string))
      }
      // 把符合条件的搜索项去重
      let set = new Set(curList.reduce((pre, cur) => [...pre, cur.turnoverNumber], []))
      // 把符合条件的搜索项赋值给下拉列表
      this.curTurnoverNumber = [...set]
    },
    /**
     * 获取搜索到的序列号列表
     * @param string 输入的字符
     */
    querySerialNumber(string) {
      // 过滤掉已选项
      let curFilter = this.curMaterialList.filter(item => item.disabled !== true && item.serialNumber)
      // 如果输入不为空
      if (string) {
        curFilter = curFilter.filter(item => item.serialNumber.startsWith(string))
      }
      // 把符合条件的搜索项赋值给下拉列表
      this.curSingleMaterialNumber = curFilter
    },
    // 选择周转码后 更新子物料工单号
    selectChange(val, row) {
      let subWorkorderIds = []
      val.map(item => {
        let subWorkorderId = this.curMaterialList.find(bt => bt.turnoverNumber === item)
        if (subWorkorderId) subWorkorderIds.push(subWorkorderId.workorderId)
      })
      row.subWorkorderIdTransfer = subWorkorderIds
      this.inputBlur()
    },
    /**
     * 序列号输入框下拉选择
     * @param item 当前行对象
     */
    serialSelect(val, row) {
      // 如果当前选项为0则不触发
      if (!val.length) return
      this.inputBlur()
      // 获取当前序列号的对应下拉项
      let curItem = this.curMaterialList.find((item) => item.serialNumber === val[0])
      // // 如果当前序列号项存在，则把周转码自动赋值
      if (!curItem) return
      // 更新子物料周转批次号
      if (row.turnoverOrPurchaseNumberTransfer.length) {
        row.turnoverOrPurchaseNumberTransfer[0] = curItem.turnoverNumber
      } else {
        this.$set(row, 'turnoverOrPurchaseNumberTransfer', [curItem.turnoverNumber])
      }
      // 更新子物料工单号
      row.subWorkorderIdTransfer[0] = curItem.workorderId
      curItem.disabled = true
    },
    removeTag(val, row) {
      let list = this.materialNumber[row.materialNumber] || []
      let curItem = list.find((item) => item.serialNumber === val)
      // 将移除的序列号设置为可选
      if (curItem) curItem.disabled = false
      if (list === this.curMaterialList) {
        // 如果移除的是当前下拉列表项的，则给当前下拉列表项重新赋值
        this.curSingleMaterialNumber = this.curMaterialList.filter(item => item.disabled !== true && item.serialNumber)
      }
    },
    // 表格中input主动失去焦点
    inputBlur() {
      let nodes = document.querySelectorAll('.el-select-dropdown')
      if (!nodes.length) return
      nodes[nodes.length - 1].style.display = 'none'
      document.getElementById('hidden_input').focus()
    },
    // 隐藏上一个打开的下拉列表
    hideSelect() {
      let nodes = document.querySelectorAll('.el-select-dropdown')
      if (nodes.length > 2) nodes[nodes.length - 2].style.display = 'none'
    }
  }
}
</script>
<style lang="less">
  .work_stage_material {
    .mes_dialog .el-dialog__body {
      padding: 0px 20px;
    }
    .table_container{
      .el-table{
        .cell{
          height: auto;
        }
      }
    }
    .defaultOptions {
      .el-autocomplete-suggestion__list {
        li {
          color: #7e8e9f !important;
        }
      }
    }
    .hasOptions {
      .el-autocomplete-suggestion__list {
        li {
          color: #333 !important;
        }
      }
    }
  }
</style>
<style scoped lang="less">
  .work_stage_material {
    .material_wrapper {
      /*display: flex;*/
      /*justify-content: space-between;*/
      padding: 20px 0px;
    }
    .table_title {
      font-size: 14px;
      line-height: 30px;
      padding-top: 10px;
    }
    .turnover_batch {
      flex: 0 0 35%;
      width: 35%;
      box-sizing: border-box;
      padding-right: 10px;
      padding-bottom: 20px;
      border-right: 1px solid #dbe1e8;
      padding-top: 20px;
    }
    .material_cont {
      flex: 0 0 65%;
      width: 65%;
      overflow: hidden;
      padding-left: 10px;
      box-sizing: border-box;
      padding-top: 20px;
      padding-bottom: 20px;
      .cut_off_rule {
        padding-top: 20px;
        border-bottom: 1px solid #dbe1e8;
      }
    }
    .el-autocomplete {
      width: 100% !important;
    }
    #hidden_input {
      display: block;
      width: 0;
      height: 0;
      border: none;
      outline: none;
      padding: 0;
    }
  }
</style>
<style lang="less">
</style>
